import { TextFieldProps_Number } from "@/pages/BCViz_new/const";
import { Paper, TextField, Button, Tab } from "@mui/material";
import style from "../_index.module.scss";
import { map, some, isUndefined, every } from "lodash";
import { setStateOnChange } from "../../utils";
import { headFileExist, uploadFile, constructBCviz, getFile } from "@/pages/BCViz_new/api";
import { idbCommonArgs, type fetchDataReturn } from "@/pages/BCviz/FileUploadSimple";
import { waitMiddleEventLoop } from "@/utils";
import { commonUseRequestParams } from "@/utils/const";
import { createOrAddIdb } from "@/utils/idb";
import { useBoolean, useSetState, useSafeState, useMemoizedFn, useRequest, useCreation, useToggle } from "ahooks";
import { useNavigate } from "react-router";
import { useSearchParams } from "react-router-dom";
import { toast } from "react-toastify";
import type { ConfirmModalProps } from "..";
import type { OriginGraphDataReadonlyArr } from "@/pages/BCviz/types";
import type { UseSafeState, UseSafeStateReturnType } from "@/pages/BCViz_new/TabPanelInput/TabPanelInput";
import { TabContext, TabList, TabPanel } from "@mui/lab";
import { notify } from "@/utils/notification";
const { error } = console;
export const getWillResolveData = ({ fileNameBEWithExt, text }: {
  readonly fileNameBEWithExt: string;
  readonly text: string;
}): fetchDataReturn => {
  return {
    fileInfo: {
      lastModified: Date.now(),
      name: fileNameBEWithExt,
      size: text.length,
      // type: headers.get('content-type') ?? '',
      // downloadUrl,
    },
    fileData: text,
  };
};
export const graphDataToText = (graphData: OriginGraphDataReadonlyArr) => graphData.map(({ u, v }) => `${u} ${v}`).join('\n');
export const getFileNameBEWithExt = (hash: string) => `${hash}.txt`;
const enum ComfirmTab {
  Preview = 'Preview',
  Parameters = 'Parameters',
}
export default function ConfirmComp (props: ConfirmModalProps & {
  readonly useHash: UseSafeStateReturnType<string>;
}) {
  const { fileName, graphData, useHash } = props;
  const text = useCreation(() => graphData ? (graphData.map(({ u, v }) => `${u} ${v}`).join('\n')) : '', [graphData]);
  const navigate = useNavigate();
  const [st_min, setSTmin] = useSetState({
    s_min: 1,
    t_min: 1
  });
  const [hash] = useHash;
  const confirmFn = useMemoizedFn(async () => {
    try {
      if (!hash) {
        return;
      }
      const fileNameFEWithExt = `${fileName}.txt`;  // 前端展示文件名
      const fileNameBEWithExt = getFileNameBEWithExt(hash);  // 后端文件名
      const fileNameBEWithExt_cohesion = `${hash}_cohesion${every(st_min, min => min === 1) ?
        '' : [st_min.s_min, st_min.t_min].map(s => `_${s}`).join('')
        }.txt`;
      const datasetsFileFolder = 'datasets/';
      // const fileNameBEWithExt = fileNameBEWithExt;//`${datasetsFileFolder}${fileNameBEWithExt}`;
      const [fetchSeeIsDatasetExist, fetchSeeIsBCvizFileExist] = await Promise.all([fileNameBEWithExt, fileNameBEWithExt_cohesion].map(headFileExist));
      // .then((res) => res.every(Boolean), () => false);

      // if (!fetchSeeIsExit) {
      // const fetchSeeIsDatasetExist = await headFileExist(fileNameBEWithExt);
      if (!fetchSeeIsDatasetExist) {
        await uploadFile(text, fileNameBEWithExt);
      }
      await waitMiddleEventLoop();
      // const fetchSeeIsBCvizFileExist = await headFileExist(fileNameBEWithExt_cohesion);
      if (!fetchSeeIsBCvizFileExist) {
        await constructBCviz({
          dataset: fileNameBEWithExt,
          ...st_min,
        });
        // }
        // await constructBCviz_old(text, fileNameBEWithExt);
        await waitMiddleEventLoop();
        // await uploadFile(text, fileNameBEWithExt);
      }
      // if (isPROD) {

      const BCviz_file = await getFile(fileNameBEWithExt_cohesion).then(res => {
        return res?.fileData;
      });
      if (!BCviz_file) {
        const errorText = `construct ${fileNameBEWithExt_cohesion} is empty!`;
        notify(errorText);
        toast.error(errorText);
        return;
      }

      const searchParams = new URLSearchParams({
        dataset: fileNameBEWithExt,
        BCviz_file: fileNameBEWithExt_cohesion,
      });
      navigate({
        pathname: '/',
        search: `?${searchParams.toString()}`
      });

      // 构建符合 HashRouter 结构的 URL
      // const targetUrl = `${window.location.origin}/#/?${searchParams.toString()}`;

      // // 在新标签页打开
      // window.open(targetUrl, '_blank');

      // }
      // const url = new URL('/', location.origin);
      // url.searchParams.set('dataset', fileNameBEWithExt);
      // url.searchParams.set('BCviz_file', `${hash}_cohesion.txt`);
      // open(url, '_blank');
      // if (isPROD) {
      const willResolveData = getWillResolveData({ fileNameBEWithExt, text });
      createOrAddIdb({
        ...idbCommonArgs, data: willResolveData, IDBValidKey: fileNameBEWithExt
      });
      // }
      // localStorage.setItem(fileNameFEWithExt, fileBEPath);
      // localStorage.setItem(`${fileName}_cohesion.txt`, fileBEPath);
      // await waitMiddleEventLoop();

      // }}

    } catch (e) {
      // alert('something error');
      error(e);
    }
  });
  const { run, loading } = useRequest(confirmFn, {
    ...commonUseRequestParams,
    manual: true,
  });
  const [tab, setTab] = useSafeState(ComfirmTab.Parameters);
  return <Paper elevation={24} className={style['Paper'] ?? ""}>
    <TabContext value={tab} >
      <TabList onChange={(e, v) => {
        setTab(v);
      }}>

        <Tab label={ComfirmTab.Parameters} value={ComfirmTab.Parameters}
          className={style['Tab'] ?? ''}
        />
        <Tab label={ComfirmTab.Preview} value={ComfirmTab.Preview}
          className={style['Tab'] ?? ''}
        />
      </TabList>
      <TabPanel value={ComfirmTab.Parameters}>
        {map(st_min, (min, key) => {
          // const label =``
          return <>
            <TextField
              fullWidth
              placeholder={key}
              label={key}
              {...TextFieldProps_Number}
              title={key}
              value={min}
              onChange={setStateOnChange(setSTmin, key)}
              required
              spellCheck
              autoCapitalize='on'
              enterKeyHint='next'
              translate='yes' //控制元素内容是否应被浏览器自动翻译。
              unselectable='off'
            />

          </>;
        })}
      </TabPanel>
      <TabPanel value={ComfirmTab.Preview}>
        <TextField
          multiline
          maxRows={9}
          InputProps={{
            readOnly: true,
          }}
          fullWidth
          label='Text of bipartite graph'
          title='Readonly TextArea'
          required
          // spellCheck
          // autoCapitalize='on'
          // enterKeyHint='next'
          translate='yes' //控制元素内容是否应被浏览器自动翻译。
          value={text}
        />
      </TabPanel>
    </TabContext>

    <Button fullWidth variant="contained" size="large"
      disabled={some(st_min, isUndefined)}
      onClick={run}
    >Confirm</Button>
  </Paper>;
}


